﻿/**
**********************************************************************************
*   Facebook.FriendsAutocomplete
**********************************************************************************
*/
Facebook.FriendsAutocomplete = function(config) {
	this.friends = config.friends || $('#friends-autocomplete input');
	this.minLength = config.minLength || 1;
	this.position = config.position || {my: 'left top', at: 'left bottom', collision: 'none'};

	this.init(); // constructor call
};
Facebook.FriendsAutocomplete.prototype = {
    // constructor
    init: function()
    {
        // DOM element cache

        // setup methods
		this.getFriends();
		this.togglePlaceholderText();
    },

	sortByFirstName: function (a, b) {
		var x = a.name.toLowerCase();
		var y = b.name.toLowerCase();
		return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	},

    getFriends: function()
    {
		FB.api('/me/friends', $.proxy(function(response) {
			var friends = $.map(response.data.sort($.proxy(this.sortByFirstName, this)), function(friend) {
				return {
					label: friend.name,
					value: friend.id
				}
			});

			this.setAutoComplete(friends);
		}, this));
	},

    setAutoComplete: function(friends)
    {
		this.friends.autocomplete({
			minLength: this.minLength,
			position: this.position,
			source: friends,
			focus: $.proxy(function(event, ui) {
				this.friends.val(ui.item.label);
				return false;
			}, this),
			select: $.proxy(function(event, ui) {
				this.friends.data('uid', ui.item.value).data('name', ui.item.label).val(ui.item.label);
				return false;
			}, this)
		})
		.data('autocomplete')._renderItem = $.proxy(function(ul, item) {
			ul.insertAfter(this.friends);
			return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a>' + item.label + '</a>')
				.appendTo(ul);
		}, this);
    },

    togglePlaceholderText: function()
    {
		this.friends.bind('focus', function () {
			if (this.value == this.defaultValue) {
				this.value = '';
			}
		}).bind('blur', function () {
			if (this.value == '') {
				this.value = this.defaultValue;
			}
		});
	}
};
